import type { Directive, DirectiveBinding } from 'vue';

interface DbPointerDownBinding extends DirectiveBinding {
    value: (event: PointerEvent) => void;
}

// 定义VUE3指令
const vDbPointerDown: Directive = {
    mounted(el: HTMLElement, binding: DbPointerDownBinding) {
        if (typeof binding.value === 'function') {
            let lastTime = 0;
            const delay = 300;
            const handler = (e: PointerEvent) => {
                const currentTime = performance.now();
                if (currentTime - lastTime < delay) {
                    binding.value(e);
                    lastTime = 0;
                } else {
                    lastTime = currentTime;
                }
            };

            // 存储事件处理器以便后续清理
            (el as any).__dbPointerDownHandler = handler;

            el.addEventListener('pointerdown', handler);
        }
    },

    unmounted(el: HTMLElement) {
        // 清理事件监听器
        const handler = (el as any).__dbPointerDownHandler;
        if (handler) {
            el.removeEventListener('pointerdown', handler);
            delete (el as any).__dbPointerDownHandler;
        }
    }
};

// 局部使用：
export default vDbPointerDown;

// 全局使用示例：
// const directives = {
//   install: function (app: any) {
//     app.directive('db-pointerdown', vDbPointerDown);
//   },
// };
//
// export default directives;